<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "0b6e024b"
    });
  daovoice('update');
  </script>














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,Android编程权威指南(第2版)," />










<meta name="keywords" content="Android,Android编程权威指南(第2版)">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第2版）学习笔记 --第25章 搜索">
<meta property="og:url" content="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-8/index.html">
<meta property="og:site_name" content="万般皆下品 唯有读书高">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/9140378-0ba92a814310e10c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/9140378-45bcb5ad456dabd9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-09-02T07:58:19.554Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第2版）学习笔记 --第25章 搜索">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/9140378-0ba92a814310e10c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-8/"/>





  <title>Android编程权威指南（第2版）学习笔记 --第25章 搜索 | 万般皆下品 唯有读书高</title>
  








</head>


   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas>
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script>
   <script type="text/javascript" src="/js/src/fireworks.js"></script>


<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">万般皆下品 唯有读书高</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">小生的学习笔记</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/31/android/Android编程权威指南/android-note-8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HyYyr Wang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/icon.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="万般皆下品 唯有读书高">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android编程权威指南（第2版）学习笔记 --第25章 搜索</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-31T15:49:03+08:00">
                2018-08-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,120
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://upload-images.jianshu.io/upload_images/9140378-0ba92a814310e10c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="u=1983816984,3550559459&amp;fm=26&amp;gp=0.jpg"></p>
<hr>
<a id="more"></a>
<h2 id="本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能"><a href="#本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能" class="headerlink" title="本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能"></a><center>本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能</center></h2><h2 id="重构"><a href="#重构" class="headerlink" title="重构"></a>重构</h2><h3 id="首先，重构-FlickerFether的代码以复用JSON数据解析逻辑"><a href="#首先，重构-FlickerFether的代码以复用JSON数据解析逻辑" class="headerlink" title="首先，重构 FlickerFether的代码以复用JSON数据解析逻辑"></a>首先，重构 FlickerFether的代码以复用JSON数据解析逻辑</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FlickrFetchr</span> </span>&#123;</span><br><span class="line">   <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String FETCH_RECENTS_METHOD = <span class="string">"flickr.photos.getRecent"</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String SEARCH_METHOD = <span class="string">"flickr.photos.search"</span>;</span><br><span class="line">    <span class="comment">//这里创建了完整的Flickr API请求URL，便利类Url。Builder可创建正确转移的参数化URL</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Uri ENDPOINT =  Uri.</span><br><span class="line">            parse(<span class="string">"https://api.flickr.com/services/rest/"</span>)</span><br><span class="line">            .buildUpon()</span><br><span class="line">            .appendQueryParameter(<span class="string">"method"</span>, <span class="string">"flickr.photos.getRecent"</span>)</span><br><span class="line">            .appendQueryParameter(<span class="string">"api_key"</span>, API_KEY)</span><br><span class="line">            .appendQueryParameter(<span class="string">"format"</span>, <span class="string">"json"</span>)</span><br><span class="line">            .appendQueryParameter(<span class="string">"nojsoncallback"</span>, <span class="string">"1"</span>)</span><br><span class="line">            .appendQueryParameter(<span class="string">"extras"</span>, <span class="string">"url_s"</span>)   <span class="comment">//该参数制定了图片的大小</span></span><br><span class="line">            <span class="comment">//这里用Url.builder()构建了完整的Flickr APi请求URL,</span></span><br><span class="line">            .build();</span><br><span class="line"></span><br><span class="line">            ...</span><br><span class="line"></span><br><span class="line">            <span class="comment">//改为私有方法</span></span><br><span class="line">    <span class="comment">// public List&lt;GalleryItem&gt; fetchItems()&#123;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;GalleryItem&gt; <span class="title">downloadGalleryItems</span><span class="params">(String url)</span> </span>&#123;</span><br><span class="line">        List&lt;GalleryItem&gt; items = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//之前的解析代码</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// String url = Uri.parse("https://api.flickr.com/services/rest/")</span></span><br><span class="line">            <span class="comment">// .buildUpon()</span></span><br><span class="line">            <span class="comment">// .appendQueryParameter("method", "flickr.photos.getRecent")</span></span><br><span class="line">            <span class="comment">// .appendQueryParameter("api_key", API_KEY)</span></span><br><span class="line">            <span class="comment">// .appendQueryParameter("format", "json")</span></span><br><span class="line">            <span class="comment">// .appendQueryParameter("nojsoncallback", "1")</span></span><br><span class="line">            <span class="comment">// .appendQueryParameter("extras", "url_s")   //该参数制定了图片的大小</span></span><br><span class="line">            <span class="comment">// //这里用Url.builder()构建了完整的Flickr APi请求URL,</span></span><br><span class="line">            <span class="comment">// .build().toString();</span></span><br><span class="line"></span><br><span class="line">            String jsonString = getUrlString(url);</span><br><span class="line">            Log.e(TAG, <span class="string">"Received JSON: "</span> + jsonString);</span><br><span class="line">            <span class="comment">//将jsonString 类型的数据装换成JSONObject而类型的</span></span><br><span class="line">            JSONObject jsonBody = <span class="keyword">new</span> JSONObject(jsonString);</span><br><span class="line">            <span class="comment">//调用parseItems()方法进行数组存储</span></span><br><span class="line">            parseItems(items,jsonBody);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JSONException e) &#123;</span><br><span class="line">            Log.e(TAG, <span class="string">"Failed to parse JSON"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException ioe) &#123;</span><br><span class="line">            Log.e(TAG, <span class="string">"Failed to fetch items"</span>, ioe);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> items;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="添加创建URL的辅助方法"><a href="#添加创建URL的辅助方法" class="headerlink" title="添加创建URL的辅助方法"></a>添加创建URL的辅助方法</h3><p>在downloadGalleryItems(String url)方法中添加一个新方法基于搜索、下载和查询创建URL<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 创建新方法用于搜索下载和查询URL参数</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="function"><span class="keyword">private</span> String <span class="title">buildUrl</span><span class="params">(String method,String query)</span></span>&#123;</span><br><span class="line">     Uri.Builder uriBuilder = ENDPOINT.buildUpon()</span><br><span class="line">             .appendQueryParameter( <span class="string">"method"</span>,method );</span><br><span class="line">     <span class="keyword">if</span> (method.equals( SEARCH_METHOD ))&#123;</span><br><span class="line">         uriBuilder.appendQueryParameter( <span class="string">"text"</span>,query );</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">return</span> uriBuilder.build().toString();</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="添加方法用于下载跟搜索"><a href="#添加方法用于下载跟搜索" class="headerlink" title="添加方法用于下载跟搜索"></a>添加方法用于下载跟搜索</h3><p>参数值是动态的，如果判断出不是搜索，他就会附加一个text参数值，如果判断出是搜索，他还会附加一个text参数值<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String FETCH_RECENTS_METHOD = <span class="string">"flickr.photos.getRecent"</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String SEARCH_METHOD = <span class="string">"flickr.photos.search"</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> List&lt;GalleryItem&gt; <span class="title">fetchRecentPhotos</span><span class="params">()</span></span>&#123;</span><br><span class="line">        String url = buildUrl(FETCH_RECENTS_METHOD,<span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">return</span> downloadGalleryItems( url );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;GalleryItem&gt; <span class="title">searchPhotos</span><span class="params">(String query)</span></span>&#123;</span><br><span class="line">        String url = buildUrl( SEARCH_METHOD,query );</span><br><span class="line">        <span class="keyword">return</span> downloadGalleryItems( url );</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="硬编码的搜索字符串"><a href="#硬编码的搜索字符串" class="headerlink" title="硬编码的搜索字符串"></a>硬编码的搜索字符串</h3><p>如果搜索字符串为空，fetchItemsTask就会执行Flickr搜索任务<br>，否则，就会默认下载最新公共图片<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">protected</span> List&lt;GalleryItem&gt; <span class="title">doInBackground</span><span class="params">(Void... voids)</span> </span>&#123;</span><br><span class="line"><span class="comment">//            try &#123;</span></span><br><span class="line"><span class="comment">//                String result = new FlickrFetchr().getUrlString("https://www.bignerdranch.com");</span></span><br><span class="line"><span class="comment">//                Log.i(TAG,"Fetched contents of URL:" + result);</span></span><br><span class="line"><span class="comment">//            &#125;catch (IOException e)&#123;</span></span><br><span class="line"><span class="comment">//                Log.e(TAG,"Failed to fetch URL: ",e);</span></span><br><span class="line"><span class="comment">//            &#125;</span></span><br><span class="line"><span class="comment">//            return new FlickrFetchr().fetchItems();</span></span><br><span class="line"><span class="comment">//            return null;</span></span><br><span class="line">            <span class="comment">//将GalleryItem对象List传递给onPostExecute()方法使用</span></span><br><span class="line"><span class="comment">//            String query = "robot";</span></span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (mQuery == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//如果搜索框内容为空,就会默认加载最新的公共图片</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> FlickrFetchr().fetchRecentPhotos();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">///如果搜索框为非空，执行搜索任务</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> FlickrFetchr().searchPhotos( mQuery );</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="SearchView的使用"><a href="#SearchView的使用" class="headerlink" title="SearchView的使用"></a>SearchView的使用</h2><h3 id="首先在在res-menu当中创建一个新的菜单XML文件"><a href="#首先在在res-menu当中创建一个新的菜单XML文件" class="headerlink" title="首先在在res/menu当中创建一个新的菜单XML文件"></a>首先在在res/menu当中创建一个新的菜单XML文件</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="utf-8"?&gt;</span><br><span class="line"><span class="tag">&lt;<span class="name">menu</span> <span class="attr">xmlns:tools</span>=<span class="string">"http://schemas.android.com/tools"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:android</span>=<span class="string">"http://schemas.android.com/apk/res/android"</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:app</span>=<span class="string">"http://schemas.android.com/apk/res-auto"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">item</span> <span class="attr">android:id</span>=<span class="string">"@+id/menu_item_search"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:title</span>=<span class="string">"@string/search"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">app:showAsAction</span>=<span class="string">"ifRoom"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">app:actionViewClass</span>=<span class="string">"android.support.v7.widget.SearchView"</span> /&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">item</span> <span class="attr">android:id</span>=<span class="string">"@+id/menu_ite_clear"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:title</span>=<span class="string">"@string/clear_search"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">app:showAsAction</span>=<span class="string">"never"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">item</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:id</span>=<span class="string">"@+id/menu_item_toggle_polling"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">android:title</span>=<span class="string">"@string/start_polling"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">app:showAsAction</span>=<span class="string">"ifRoom"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">menu</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="然后让其响应点击事件"><a href="#然后让其响应点击事件" class="headerlink" title="然后让其响应点击事件"></a>然后让其响应点击事件</h3><p>在OnCreate()方法当中调用setHasOptionsMenu(true)方法让fragment接受菜单回调方法<br>，然后，覆盖onCreateOptionsMenu(…)方法并实例化菜单XMl文件<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(@Nullable Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate( savedInstanceState );</span><br><span class="line">        <span class="comment">//在Activity重新创建时可以不完全销毁Fragment，以便Fragment可以恢复</span></span><br><span class="line">        setRetainInstance( <span class="keyword">true</span> );</span><br><span class="line"></span><br><span class="line">        <span class="comment">//让fragment接收菜单回调方法</span></span><br><span class="line">        setHasOptionsMenu( <span class="keyword">true</span> );</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreateOptionsMenu</span><span class="params">(Menu menu, MenuInflater menuInflater)</span></span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.onCreateOptionsMenu( menu, menuInflater );</span><br><span class="line">    menuInflater.inflate( R.menu.fragment_photo_gallery, menu );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="响应用户搜索"><a href="#响应用户搜索" class="headerlink" title="响应用户搜索"></a>响应用户搜索</h3><h4 id="SearchView-OnQueryTextListener-接口已经提供了接受回调的方式，更新onCreateOptionsMenu-…-方法，实现这个监听方法"><a href="#SearchView-OnQueryTextListener-接口已经提供了接受回调的方式，更新onCreateOptionsMenu-…-方法，实现这个监听方法" class="headerlink" title="SearchView.OnQueryTextListener()接口已经提供了接受回调的方式，更新onCreateOptionsMenu(…)方法，实现这个监听方法"></a>SearchView.OnQueryTextListener()接口已经提供了接受回调的方式，更新onCreateOptionsMenu(…)方法，实现这个监听方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreateOptionsMenu</span><span class="params">(Menu menu, MenuInflater menuInflater)</span></span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.onCreateOptionsMenu( menu, menuInflater );</span><br><span class="line">    menuInflater.inflate( R.menu.fragment_photo_gallery, menu );</span><br><span class="line"></span><br><span class="line">      <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 实现SearchView。OnQueryTextListener监听方法</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//首先从菜单中取出MenuItem并把它保存在searchItem变量当中</span></span><br><span class="line">    <span class="keyword">final</span> MenuItem searchItem = menu.findItem( R.id.menu_item_search );</span><br><span class="line"></span><br><span class="line">    <span class="comment">//使用getActionView()取出searchView</span></span><br><span class="line">    <span class="keyword">final</span> SearchView searchView = (SearchView) searchItem.getActionView();</span><br><span class="line">    searchView.setOnQueryTextListener( <span class="keyword">new</span> SearchView.OnQueryTextListener() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onQueryTextSubmit</span><span class="params">(String query)</span> </span>&#123;</span><br><span class="line">        Log.d( TAG, <span class="string">"QueryTextSubmit: "</span> + query );</span><br><span class="line">        updateItems();</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onQueryTextChange</span><span class="params">(String newText)</span> </span>&#123;</span><br><span class="line">        Log.d( TAG, <span class="string">"QueryTextChange: "</span> + newText );</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">updateItems</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">new</span> fetchItemsTask().execute();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="最后在onCreate-…-方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems-封装方法"><a href="#最后在onCreate-…-方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems-封装方法" class="headerlink" title="最后在onCreate(…)方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems()封装方法"></a>最后在onCreate(…)方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems()封装方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(@Nullable Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate( savedInstanceState );</span><br><span class="line">        setRetainInstance( <span class="keyword">true</span> );</span><br><span class="line">        <span class="comment">//让fragment接收菜单回调方法</span></span><br><span class="line">        setHasOptionsMenu( <span class="keyword">true</span> );</span><br><span class="line">        <span class="comment">//execute()会启动AsyncTask</span></span><br><span class="line"><span class="comment">//        new FetchItemsTask().execute();</span></span><br><span class="line">        updateItems();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="使用SharedPreferrences-实现轻量级数据储存"><a href="#使用SharedPreferrences-实现轻量级数据储存" class="headerlink" title="使用SharedPreferrences 实现轻量级数据储存"></a>使用SharedPreferrences 实现轻量级数据储存</h2><h3 id="什么是Sharepreferrences"><a href="#什么是Sharepreferrences" class="headerlink" title="什么是Sharepreferrences?"></a>什么是Sharepreferrences?</h3><p><img src="https://upload-images.jianshu.io/upload_images/9140378-45bcb5ad456dabd9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="images.jpg"></p>
<ul>
<li>shared preferences 本质上就是文件系统中的文件，可使用 SharedPreferences 类读写它。</li>
<li>SharedPreferences 实例用起来更像一个键值对仓库(类似于 Bundle)，但它可以通过持久化存储保存数据。键值对中的键为字符串，而值是原子数据类型。</li>
<li>它们实际上是一种简单的 XML 文件，但SharedPreferences 类已屏蔽了读写文件的实现细节。shared preferences 文件保存在应用沙盒中，所以，类似密码这样的敏感信息不应该用它来保存。<br><ul>
<li>要获得定制的 SharedPreferences 实例,可使用Context.getSharedPreferences (String,int)方法。</li>
<li>这种情况下，最好使用PreferenceManager. getDefaultSharedPreferences(Context)方法，该方法会返回具有私有权限和默认名称的实例(仅在当前应用内可用)。</li>
</ul>
</li>
</ul>
<h3 id="使用SharedPreferrences"><a href="#使用SharedPreferrences" class="headerlink" title="使用SharedPreferrences"></a>使用SharedPreferrences</h3><h4 id="添加一个QUeryPreferences-java类管理保存的查询字符串"><a href="#添加一个QUeryPreferences-java类管理保存的查询字符串" class="headerlink" title="添加一个QUeryPreferences.java类管理保存的查询字符串"></a>添加一个<a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/blob/master/PhotoGallery/app/src/main/java/com/example/lab/android/nuc/photogallery/Base/QueryPreferences.java" target="_blank" rel="noopener">QUeryPreferences.java</a>类管理保存的查询字符串</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">QueryPreferences</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String PREF_SEARCH_QUERY = <span class="string">"searchQuery"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通过SharePreference得到数据</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getStoreQuery</span><span class="params">(Context context)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> PreferenceManager.getDefaultSharedPreferences( context )</span><br><span class="line">                .getString( PREF_SEARCH_QUERY,<span class="keyword">null</span> );</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//通过SharePreference写入数据</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setStoreQuery</span><span class="params">(Context context,String query)</span></span>&#123;</span><br><span class="line">        PreferenceManager.getDefaultSharedPreferences( context )</span><br><span class="line">                .edit()</span><br><span class="line">                .putString( PREF_SEARCH_QUERY,query )</span><br><span class="line">                .apply();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="储存用户提交的信息"><a href="#储存用户提交的信息" class="headerlink" title="储存用户提交的信息"></a>储存用户提交的信息</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreateOptionsMenu</span><span class="params">(Menu menu, MenuInflater menuInflater)</span> </span>&#123;</span><br><span class="line">        searchView.setOnQueryTextListener( <span class="keyword">new</span> SearchView.OnQueryTextListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onQueryTextSubmit</span><span class="params">(String query)</span> </span>&#123;</span><br><span class="line">                Log.d( TAG, <span class="string">"QueryTextSubmit: "</span> + query );</span><br><span class="line">                <span class="comment">//储存用户提交的查询信息</span></span><br><span class="line">                QueryPreferences.setStoreQuery( getActivity(), query );</span><br><span class="line">                updateItems();</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onQueryTextChange</span><span class="params">(String newText)</span> </span>&#123;</span><br><span class="line">                Log.d( TAG, <span class="string">"QueryTextChange: "</span> + newText );</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="清除查询信息"><a href="#清除查询信息" class="headerlink" title="清除查询信息"></a>清除查询信息</h4><p>在用户从溢出菜单选择Clear Search 选项时清除储存的查询信息(设置为 null )<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onOptionsItemSelected</span><span class="params">(MenuItem item)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> (item.getItemId()) &#123;</span><br><span class="line">            <span class="keyword">case</span> R.id.menu_ite_clear:</span><br><span class="line">                QueryPreferences.setStoreQuery( getActivity(), <span class="keyword">null</span> );</span><br><span class="line">                updateItems();</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            <span class="keyword">default</span>:</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">super</span>.onOptionsItemSelected( item );</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="优化应用"><a href="#优化应用" class="headerlink" title="优化应用"></a>优化应用</h2><h3 id="让SearchView文本框默认显示已保存的查询信息"><a href="#让SearchView文本框默认显示已保存的查询信息" class="headerlink" title="让SearchView文本框默认显示已保存的查询信息"></a>让SearchView文本框默认显示已保存的查询信息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreateOptionsMenu</span><span class="params">(Menu menu, MenuInflater menuInflater)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">        searchView.setOnQueryTextListener( <span class="keyword">new</span> SearchView.OnQueryTextListener() &#123;</span><br><span class="line">            ...</span><br><span class="line"></span><br><span class="line">        &#125; );</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 优化应用</span></span><br><span class="line"><span class="comment">         * 回调方法设置搜索文本框的值</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        searchView.setOnClickListener( <span class="keyword">new</span> View.OnClickListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onClick</span><span class="params">(View v)</span> </span>&#123;</span><br><span class="line">                String query = QueryPreferences.getStoreQuery( getActivity() );</span><br><span class="line">                searchView.setQuery( query, <span class="keyword">false</span> );</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; );</span><br><span class="line">    &#125;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="优化练习：深度优化PHotoGallery应用"><a href="#优化练习：深度优化PHotoGallery应用" class="headerlink" title="优化练习：深度优化PHotoGallery应用"></a>优化练习：深度优化PHotoGallery应用</h2><ul>
<li>用户一提交搜索,就隐藏软键盘,收起 Searchview视图(回<br>到只显示搜索按钮的初始状态)</li>
<li>用户一提交搜索,就初始化 Recyctervie显示一个搜索结果加载状态界面(使用状态指示器)。下载到JSON数据之后,就删除状态指示器。也就是说,一旦开始下载图片就不应显示加载状态了。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhotoGalleryFragment</span> <span class="keyword">extends</span> <span class="title">VisibleFragment</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCreateOptionsMenu</span><span class="params">(Menu menu, MenuInflater menuInflater)</span> </span>&#123;</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line">        searchView.setOnQueryTextListener( <span class="keyword">new</span> SearchView.OnQueryTextListener() &#123;</span><br><span class="line">        Log.d( TAG, <span class="string">"QueryTextSubmit: "</span> + query );</span><br><span class="line"></span><br><span class="line">                <span class="comment">//储存用户提交的查询信息</span></span><br><span class="line">                QueryPreferences.setStoreQuery( getActivity(), query );</span><br><span class="line">                <span class="comment">// 优化隐藏键盘</span></span><br><span class="line">               <span class="keyword">if</span> (searchView != <span class="keyword">null</span>)&#123;</span><br><span class="line">                   <span class="comment">//得到输入管理对象</span></span><br><span class="line">                   InputMethodManager inputMethodManager = (InputMethodManager) getActivity()</span><br><span class="line">                           .getSystemService( Context.INPUT_METHOD_SERVICE );</span><br><span class="line">                   <span class="keyword">if</span> (inputMethodManager != <span class="keyword">null</span>)&#123;</span><br><span class="line">                       <span class="comment">/*</span></span><br><span class="line"><span class="comment">                        这将让键盘在所有的情况下都被隐藏，但是一般我们在点击搜索按钮后,输入法都会乖乖的自动隐藏的。</span></span><br><span class="line"><span class="comment">                        */</span></span><br><span class="line"></span><br><span class="line">                       <span class="comment">// 输入法如果是显示状态，那么就隐藏输入法</span></span><br><span class="line">                       inputMethodManager.hideSoftInputFromWindow( searchView.getWindowToken(),<span class="number">0</span> );</span><br><span class="line">                   &#125;</span><br><span class="line">                   searchView.onActionViewCollapsed();<span class="comment">// 不获取焦点</span></span><br><span class="line">               &#125;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onQueryTextChange</span><span class="params">(String newText)</span> </span>&#123;</span><br><span class="line">                Log.d( TAG, <span class="string">"QueryTextChange: "</span> + newText );</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; );</span><br><span class="line">    &#125;</span><br><span class="line">  ...</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<hr>
<p>Github 具体代码：<a href="https://github.com/wanghao15536870732/Android-programming-authority-guide/blob/master/PhotoGallery/app/src/main/java/com/example/lab/android/nuc/photogallery/Fragment/PhotoGalleryFragment.java" target="_blank" rel="noopener">hyyyr wang.github.io</a></p>

      
    </div>
    
    
    

    

    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"><i class="fa fa-tag"></i> Android</a>
          
            <a href="/tags/Android编程权威指南-第2版/" rel="tag"><i class="fa fa-tag"></i> Android编程权威指南(第2版)</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/31/android/Android编程权威指南/android-note-7/" rel="next" title="Android编程权威指南（第2版）学习笔记 --第24章 Looper、Handler和HandlerThread">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第2版）学习笔记 --第24章 Looper、Handler和HandlerThread
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/31/android/Android编程权威指南/android-note-9/" rel="prev" title="Android编程权威指南（第2版）学习笔记 --第26章 后台服务">
                Android编程权威指南（第2版）学习笔记 --第26章 后台服务 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zOTQxMi8xNTkzOQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/uploads/icon.jpg"
                alt="HyYyr Wang" />
            
              <p class="site-author-name" itemprop="name">HyYyr Wang</p>
              <p class="site-description motion-element" itemprop="description">我不是程序员，也不是设计师，只是喜欢编程，热爱python，碰巧有一些想法跟一台电脑</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/wanghao15536870732" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:hyyyrwang@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/183791128" target="_blank" title="豆瓣">
                      
                        <i class="fa fa-fw fa-globe"></i>豆瓣</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/be-forever-82/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/964bc0f1e88e" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-globe"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_41005535" target="_blank" title="CSND">
                      
                        <i class="fa fa-fw fa-globe"></i>CSND</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="npm install hexo-wordcount --save" title="秋冬夜漫长" target="_blank">秋冬夜漫长</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://angus-liu.github.io" title="Angus-Liu" target="_blank">Angus-Liu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://innofang.github.io" title="Inno Fang" target="_blank">Inno Fang</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://barackbao.com" title="Barack Bao" target="_blank">Barack Bao</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wmpscc.github.io" title="wmpscc" target="_blank">wmpscc</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://kentanvictor.github.io" title="JohnnyTan" target="_blank">JohnnyTan</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://xmmmmmovo.github.io/" title="xmmmmmovo Zha" target="_blank">xmmmmmovo Zha</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能"><span class="nav-number">1.</span> <span class="nav-text">本章的任务是使用SearchView为PhotoGalllery应用添加Flickr图片搜索功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重构"><span class="nav-number">2.</span> <span class="nav-text">重构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#首先，重构-FlickerFether的代码以复用JSON数据解析逻辑"><span class="nav-number">2.1.</span> <span class="nav-text">首先，重构 FlickerFether的代码以复用JSON数据解析逻辑</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加创建URL的辅助方法"><span class="nav-number">2.2.</span> <span class="nav-text">添加创建URL的辅助方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加方法用于下载跟搜索"><span class="nav-number">2.3.</span> <span class="nav-text">添加方法用于下载跟搜索</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#硬编码的搜索字符串"><span class="nav-number">2.4.</span> <span class="nav-text">硬编码的搜索字符串</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SearchView的使用"><span class="nav-number">3.</span> <span class="nav-text">SearchView的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#首先在在res-menu当中创建一个新的菜单XML文件"><span class="nav-number">3.1.</span> <span class="nav-text">首先在在res/menu当中创建一个新的菜单XML文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#然后让其响应点击事件"><span class="nav-number">3.2.</span> <span class="nav-text">然后让其响应点击事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#响应用户搜索"><span class="nav-number">3.3.</span> <span class="nav-text">响应用户搜索</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#SearchView-OnQueryTextListener-接口已经提供了接受回调的方式，更新onCreateOptionsMenu-…-方法，实现这个监听方法"><span class="nav-number">3.3.1.</span> <span class="nav-text">SearchView.OnQueryTextListener()接口已经提供了接受回调的方式，更新onCreateOptionsMenu(…)方法，实现这个监听方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最后在onCreate-…-方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems-封装方法"><span class="nav-number">3.4.</span> <span class="nav-text">最后在onCreate(…)方法中，删除创建和执行FetchItemsTask的那行代码，改用updateItems()封装方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用SharedPreferrences-实现轻量级数据储存"><span class="nav-number">4.</span> <span class="nav-text">使用SharedPreferrences 实现轻量级数据储存</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是Sharepreferrences"><span class="nav-number">4.1.</span> <span class="nav-text">什么是Sharepreferrences?</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用SharedPreferrences"><span class="nav-number">4.2.</span> <span class="nav-text">使用SharedPreferrences</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#添加一个QUeryPreferences-java类管理保存的查询字符串"><span class="nav-number">4.2.1.</span> <span class="nav-text">添加一个QUeryPreferences.java类管理保存的查询字符串</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#储存用户提交的信息"><span class="nav-number">4.2.2.</span> <span class="nav-text">储存用户提交的信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#清除查询信息"><span class="nav-number">4.2.3.</span> <span class="nav-text">清除查询信息</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化应用"><span class="nav-number">5.</span> <span class="nav-text">优化应用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#让SearchView文本框默认显示已保存的查询信息"><span class="nav-number">5.1.</span> <span class="nav-text">让SearchView文本框默认显示已保存的查询信息</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化练习：深度优化PHotoGallery应用"><span class="nav-number">6.</span> <span class="nav-text">优化练习：深度优化PHotoGallery应用</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HyYyr Wang</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>


<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span> </span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有 <span id="busuanzi_value_site_uv"></span> 人看过我的博客啦
</span>
</div>





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共33.8k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
